using System;

using agsXMPP.protocol.extensions.chatstates;

using VSTalk.Engine.Core.ChatSession;
using VSTalk.Engine.Core.Feed;
using VSTalk.Engine.Core.XmppUtils;
using VSTalk.Model;

using agsXMPP.protocol.client;

namespace VSTalk.Engine.Core.XmppCommunication.Services.MessageService
{
    public class MessageService : BaseCommunicationService, IMessageService
    {
        private static DirectMessageProvider _provider;

        private DirectMessageProvider Provider
        {
            get
            {
                if (_provider == null)
                {
                    _provider = new DirectMessageProvider();
                    AppServices.Get<IMessageFeed>().RegisterProvider(_provider);
                }
                return _provider;
            }
        }

        public void SendMessage(IInterlocutorChatSession chatSession, Message outMessage)
        {
            outMessage.To = chatSession.ActiveResource == null 
                ? XmppIdConverter.Jid(chatSession.Interlocutor) 
                : chatSession.ActiveResource.Jid;
            //outMessage.From = ClientContext.Jid;
            outMessage.Type = MessageType.chat;
            Connection.Send(outMessage);

            // agsXMPP doesn't fire onMessage event automatically, 
            // so push message to feed right here
            var contactMessage = new FeedMessage();
            contactMessage.XmppMessage = outMessage;
            contactMessage.Date = DateTime.Now;
            contactMessage.ClientId = Client.Id;

            Provider.EmitMessage(contactMessage);
        }

        public void SendMessage(Room to, Message outMessage)
        {
            outMessage.To = XmppIdConverter.Jid(to);
            outMessage.Type = MessageType.groupchat;
            Connection.Send(outMessage);
        }
    }
}